package com.ims.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ims.dao.StatusMapper;
import com.ims.pojo.Status;
import com.ims.service.StatusService;
import com.ims.util.PageResult;
import com.ims.util.QueryPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zk
 * @date: 2022/9/4 16:01
 */
@Service
public class StatusServiceImpl extends ServiceImpl<StatusMapper, Status> implements StatusService {

    @Autowired
    private StatusMapper statusMapper;

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult<JSONObject> findPage(QueryPageBean queryPageBean) {
        QueryWrapper<Status> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(queryPageBean.getQueryString())) {
            wrapper.like("device_name", queryPageBean.getQueryString());
        }
        if (StringUtils.hasText(queryPageBean.getOrderColumn()) && StringUtils.hasText(queryPageBean.getOrderRule())) {
            wrapper.orderBy(true, queryPageBean.getOrderRule().equals("asc"), queryPageBean.getOrderColumn());
        }
        Page<Status> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        page = statusMapper.selectPage(page, wrapper);
        List<Status> statusList = page.getRecords();

        // 字符串转json
        List<JSONObject> result = new ArrayList<>();
        for (Status status : statusList) {
            JSONObject item = new JSONObject();
            item.put("id", status.getId());
            item.put("device_id", status.getDeviceId());
            item.put("device_name", status.getDeviceName());
            item.put("status_info", JSONObject.parse(status.getStatusInfo()));
            item.put("event_time", status.getEventTime());
            result.add(item);
        }

        return new PageResult(page.getTotal(), result);
    }
}
